package org.lex.swing.widgets.console;

import java.awt.TextArea;

import javax.swing.event.EventListenerList;

import org.lex.utils.SystemProperties;

public abstract class AbstractAWTConsole extends TextArea implements IConsole {
	private static final String nl = SystemProperties.lineSeparator();
	private EventListenerList listenerList = new EventListenerList();
	private ConsoleWriter out = null;
	private ConsoleWriter err = null;

	public AbstractAWTConsole(int rows, int columns) {
		super(rows, columns);
	}

	public abstract AbstractAWTConsole print(Object o);

	public ConsoleWriter getErr() {
		if (null == err) {
			err = new ConsoleWriter(new ConsoleWriter.Printer(this) {
				@Override
				IConsole print(Object o) {
					return this.console.error(o);
				}
			});
		}
		return err;
	}

	public ConsoleWriter getOut() {
		if (null == out) {
			out = new ConsoleWriter(new ConsoleWriter.Printer(this) {
				@Override
				IConsole print(Object o) {
					return this.console.print(o);
				}
			});
		}
		return out;
	}

	public IConsole println() {
		return this.print(nl);
	}

	public AbstractAWTConsole println(Object o) {
		return this.print(o).print(nl);
	}

	public AbstractAWTConsole error(Object o) {
		return this.print("***").println(o);
	}

	public void addConsoleListener(ConsoleListener l) {
		this.listenerList.add(ConsoleListener.class, l);
	}

	public void removeConsoleListener(ConsoleListener l) {
		this.listenerList.remove(ConsoleListener.class, l);
	}

	protected void fireConsoleExecute(String command) {
		// Guaranteed to return a non-null array
		Object[] listeners = listenerList.getListenerList();
		// Process the listeners last to first, notifying
		// those that are interested in this event
		for (int i = listeners.length - 2; i >= 0; i -= 2)
			if (listeners[i] == ConsoleListener.class)
				((ConsoleListener) listeners[i + 1]).execute(command);
	}
}
